import os
import subprocess
from datetime import datetime

# 记录遍历的时间信息
record_file = "gitpull.record"
# 最大遍历深度
max_depth = 4
# 是否每次git pull，过后都保存pull_record文件
# False会等到遍历完的时候，以覆盖的方式一次性写入文件。
write_record_when_pull = True
pull_record = {}


class record_obj:
    def __init__(self, date, pull_success):
        self.date = date
        self.pull_success = pull_success


def record_pull_time(directory, max_depth):
    if max_depth <= 0:
        return
    current_date = datetime.now().strftime("%Y-%m")
    for sub_dir in os.listdir(directory):
        full_path = os.path.join(directory, sub_dir)
        if os.path.isdir(full_path):
            # 检查是否已经执行过 git pull
            mydata = pull_record.get(sub_dir)
            if mydata is not None and mydata.date == current_date:
                print(f"Git pull has already been executed in {full_path}. Skipping...")
                continue

            if os.path.exists(os.path.join(full_path, ".git")):
                print(f"Pulling from: {full_path}")
                result = subprocess.run(["git", "pull"], cwd=full_path)
                # CompletedProcess(args=['git', 'pull'], returncode=1)
                pull_success = result.returncode == 0
                if not pull_success:
                    print(f"Pulling failed from: {full_path}")
                pull_record[sub_dir] = record_obj(current_date, pull_success)
                if write_record_when_pull:
                    print(f"Write_record after git pull, append dir:{full_path}")
                    write_record()
            else:
                record_pull_time(full_path, max_depth - 1)


def read_record():
    if os.path.exists(record_file):
        with open(record_file, "r") as f:
            lines = f.readlines()
            for line in lines:
                parts = line.strip().split(",")
                pull_record[parts[0]] = record_obj(
                    parts[1], len(parts) > 2 and parts[2] == "True"
                )


def write_record():
    # 更新记录文件
    with open(record_file, "w") as f:
        for subdir, record_obj in pull_record.items():
            f.write(f"{subdir},{record_obj.date},{record_obj.pull_success}\n")


if __name__ == "__main__":
    read_record()
    record_pull_time(".", max_depth)
    if not write_record_when_pull:
        write_record()
    print("Git pull done!")
